package com.hourse.platform.config;

import com.hourse.platform.vo.PageData;
import com.hourse.platform.common.ErrorMsg;
import com.hourse.platform.exception.AppException;
import com.hourse.platform.exception.ValidateException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileNotFoundException;

@ControllerAdvice
public class ControllerExceptionConfig {

    /**
     * @功能描述: 【手动设置服务信息异常】
     */
    @ExceptionHandler(value = AppException.class)
    @ResponseBody
    public PageData exceptionHandle(AppException e) {
        return PageData.ERROR(e.getCode(), e.getMsg());
    }

    /**
     * @功能描述: 【服务异常】
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public PageData exceptionHandle(Exception e) {
        e.printStackTrace();
        return PageData.ERROR(ErrorMsg.SYSTEM_ERR);
    }

    /**
     * @功能描述: 【消息体校验未通过】
     */
    @ExceptionHandler(value = ValidateException.class)
    @ResponseBody
    public PageData exceptionHandle(ValidateException e) {
        return PageData.ERROR(ErrorMsg.BEAN_CHECK_ERR.code(), e.getMsg());
    }

    /**
     * FileNotFoundException
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = FileNotFoundException.class)
    @ResponseBody
    public PageData exceptionHandle(FileNotFoundException e) {
        e.printStackTrace();
        return PageData.ERROR(ErrorMsg.FILE_NOT_FOUND.code(), ErrorMsg.FILE_NOT_FOUND.msg());
    }


    /**
     * BindException
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public PageData handlerUnexpectedTypeException(MethodArgumentNotValidException ex) {
        BindingResult result = ex.getBindingResult();
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            if (fieldError != null) {
                return PageData.ERROR(ErrorMsg.BEAN_CHECK_ERR.code(), fieldError.getDefaultMessage());
            }
        }
        return PageData.ERROR(ErrorMsg.SYSTEM_ERR);

    }
}
